from datetime import datetime

from utills.encryptUtill import encrypt
from userServer.models import UserInfo

#用户注册
def registerdao(username, password,email):
    UserInfo.objects.create(username=username, password=encrypt(password), email=email)

#用户登录
def logindao(username, password):
    if UserInfo.objects.filter(username=username, password=encrypt(password)).exists():
        return True
    else:
        return False
#修改密码
def updatepwddao(username, oldPassword,newPassword):
    if UserInfo.objects.filter(username=username, password=encrypt(oldPassword)).exists():
        #修改密码
        UserInfo.objects.filter(username=username).update(password=encrypt(newPassword))
        return True
    else:
        return False

#注销用户，将用户的is_delete改为false
def logoutdao(username):
    """查询注销状态，如果已经注销则抛出异常"""
    if UserInfo.objects.filter(username=username).exists():
        user = UserInfo.objects.get(username=username)
        if user.is_delete:
            return False
    else:
        UserInfo.objects.filter(username=username).update(is_delete=True)
        return True

#修改邮箱
def updateemaildao(username,email):
    if UserInfo.objects.filter(username=username).exists():
        #修改邮箱的时候顺便修改update_time为当前时间。
        UserInfo.objects.filter(username=username).update(email=email)
        return True
    else:
        return False

#获取用户ID
def getUserId(username):
    if UserInfo.objects.filter(username=username).exists():
        user = UserInfo.objects.get(username=username)
        return user.id
    else:
        return False

#获取用户注销状态
def getUserIsDelete(username):
    if UserInfo.objects.filter(username=username).exists():
        user = UserInfo.objects.get(username=username)
        return user.is_delete
    else:
        return False

#找回密码验证
def isVerifyEmail(username,email):
    if UserInfo.objects.filter(username=username,email=email).exists():
        user = UserInfo.objects.get(username=username,email=email)
        return True
    else:
        return False
#找回密码
def findPassworddao(username,email,newPassword):
    if UserInfo.objects.filter(username=username,email=email).exists():
        user = UserInfo.objects.get(username=username,email=email)
        user.password = encrypt(newPassword)
        user.save()
        return True
    else:
        return False